import { defineStore } from 'pinia'
import type { IDialog, IHandleApi } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IPlanInfo, IPlanStats } from '@/types/plan.ts'
import {
  addPlanApi,
  deletePlanApi,
  queryPlanApi, queryPlanStatsApi,
  setPlanStatusApi,
  updatePlanApi
} from '@/apis/plan.ts'

export const usePlanStore = defineStore('plan', {
  state: () => ({
    planList: [] as IPlanInfo[],
    queryInfo: {
      planType: 'all',
      orderType: 'date'
    },
    planStats: {
      totalCount: 0,
      completedCount: 0,
      currentCount: 0,
      remainCount: 0
    } as IPlanStats,
    planApiType: 'ADD' as IHandleApi,
    currentPlan: {
      id: 0,
      title: '',
      content: '',
      date: '',
      startTime: '',
      endTime: '',
      alterTime: '',
      email: '',
      tag: '',
      isTop: 0,
      priority: 0,
      completed: 0
    } as IPlanInfo,
    planDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IPlanInfo>,
    isRefresh: false
  }),
  actions: {
    async queryPlan() {
      this.planList = await queryPlanApi({
        orderType: this.queryInfo.orderType,
        planType: this.queryInfo.planType
      })
    },
    async queryStats() {
      this.planStats = await queryPlanStatsApi()
    },
    async setPlanStatus(id: number, status: boolean) {
      await setPlanStatusApi(id, status)
      await this.refreshInfo()
    },
    async handlePlanApi(plan: IPlanInfo) {
      switch (this.planApiType) {
        case 'ADD':
          await addPlanApi(plan)
          ElMessage.success('新增计划成功')
          break
        case 'UPDATE':
          await updatePlanApi(plan.id as number, plan)
          ElMessage.success('更新计划成功')
          break
        case 'DELETE':
          await deletePlanApi(plan.id as number)
          ElMessage.success('删除计划成功')
          break
        default:
          break
      }
      this.planDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryPlan()
      await this.queryStats()
      this.isRefresh = !this.isRefresh
    },
    getEmptyPlan(): IPlanInfo {
      return {
        email: '',
        alterTime: null,
        completed: 0,
        content: '',
        date: null,
        endTime: null,
        isTop: 0,
        priority: 2,
        startTime: null,
        tag: '',
        title: ''
      }
    }
  }
})
